{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 基于物品的协同过滤"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#导入必要的工具包\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "import pickle\n",
    "import scipy.io as sio\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#用户和item的索引\n",
    "user_index = pickle.load(open(\"user_index.pkl\",'rb'))\n",
    "item_index = pickle.load(open(\"item_index.pkl\",'rb'))\n",
    "\n",
    "n_users = len(user_index)\n",
    "n_items = len(item_index)\n",
    "\n",
    "#用户-物品关系矩阵\n",
    "user_item_scores = sio.mmread(\"user_items_scores\").todense()\n",
    "\n",
    "#倒排表\n",
    "user_items = pickle.load(open(\"user_items.pkl\",'rb'))\n",
    "item_users = pickle.load(open(\"item_users.pkl\",'rb'))\n",
    "\n",
    "similarity_matrix = pickle.load(open(\"items_similarity.pkl\",'rb'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'similarity_matrix' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-3-ae5e16c3fdbd>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     11\u001b[0m \u001b[0mcur_item_index\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     12\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcur_user_items\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m     \u001b[0mcur_similarity_matrix\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcur_item_index\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msimilarity_matrix\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     14\u001b[0m     \u001b[0mcur_item_index\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcur_item_index\u001b[0m \u001b[0;34m+\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     15\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'similarity_matrix' is not defined"
     ]
    }
   ],
   "source": [
    "#根据相似度矩阵进行推荐（相似度矩阵由于电脑内存限制。相似度矩阵无法生成）\n",
    "cur_user = '90d2fcb1dbe47dc1e9442587e259811a0437a13f'\n",
    "\n",
    "cur_user_id = user_index[cur_user]\n",
    "cur_user_items = user_items[cur_user_id]\n",
    "\n",
    "n_cur_user_items = len(cur_user_items)\n",
    "user_sim_scores = np.zeros(n_cur_user_items)\n",
    "\n",
    "cur_similarity_matrix = np.matrix(np.zeros(shape=(n_cur_user_items,n_items)),float)\n",
    "\n",
    "cur_item_index=0\n",
    "for i in cur_user_items:\n",
    "    cur_similarity_matrix[cur_item_index,:] = similarity_matrix[i,:]\n",
    "    cur_item_index = cur_item_index +1\n",
    "\n",
    "user_sim_scores = cur_similarity_matrix.sum(axis=0)/float(cur_similarity_matrix.shape[0])\n",
    "user_sim_scores = np.array(user_sim_scores)[0].tolist()\n",
    "\n",
    "sort_index = sorted(((e,i) for i,e in enumerate(list(user_sim_scores))), reverse=True)\n",
    "\n",
    "columns = ['user_id','item','score','rank']\n",
    "\n",
    "df = pd.DataFrame(columns = columns)\n",
    "\n",
    "rank=1\n",
    "for i in range(0,len(sort_index)):\n",
    "    cur_item_index = sort_index[i][1]\n",
    "    cur_item = list(item_index.keys())[list(item_index.values()).index(cur_item_index)]\n",
    "    \n",
    "    if -np.isnan(sort_index[i][0]) and cur_item_index not in cur_user_items and rank <=20:\n",
    "        df.loc[len(df)]=[cur_user,cur_item,sort_index[i][0],rank]\n",
    "        rank = rank+1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'df' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-4-00cf07b74dcd>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdf\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'df' is not defined"
     ]
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
